package com.situ.mall.admin.interceptor;

import com.situ.mall.admin.exception.NoLoginException;
import com.situ.mall.common.util.RequestUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//处理器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        证明有没有登陆，从session中取出打上的标记
//        请求包在session里
        Object o = RequestUtil.getCurrent();
        if (o == null) {
            if (isAjax(request)) {
                throw new NoLoginException();
            } else {
                response.sendRedirect("/login");
            }
        }
        return o != null;
    }
    private boolean isAjax(HttpServletRequest request) {
        String s = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(s);
    }

}
